import request from '@/utils/request'
import config from '@/config'
import { getToken } from '@/utils/auth'

// 1. 登录API
export function elderlyLogin(username, password) {
  const data = {
    username,
    password
  }
  return request({
    // 后端实际登录路径为 /login（通过 Nginx 的 /api 反向代理）
    url: '/login',
    method: 'post',
    data: data,
    headers: {
      isToken: false
    }
  })
}

// 2. 用户注册API
export function addUser(userId, password) {
  const data = {
    userId,
    password
  }
  return request({
    url: '/elderly/addUser',
    method: 'post',
    data: data,
    headers: {
      isToken: false
    }
  })
}

// 3. 修改密码API
export function updatePassword(userId, password, newPassword) {
  const data = {
    userId,
    password,
    newPassword
  }
  return request({
    url: '/elderly/updatePwd',
    method: 'post',
    data: data
  })
}

// 4. AI会话API（流式响应）
export function streamChat(userId, relativeId, query) {
  const data = {
    userId,
    relativeId,
    query
  }
  return request({
    url: '/elderly/stream',
    method: 'post',
    data: data
  })
}

// 5. 新增本人画像
export function addUserProfile(data) {
  return request({
    url: '/elderly/user',
    method: 'post',
    data: data
  })
}

// 5. 修改本人画像
export function updateUserProfile(data) {
  return request({
    url: '/elderly/user',
    method: 'put',
    data: data
  })
}

// 6. 查询本人画像
export function getUserProfile(userId) {
  return request({
    url: `/elderly/user/selectUser/${userId}`,
    method: 'get'
  })
}

// 7. 新增亲属画像
export function addRelativeProfile(data) {
  return request({
    url: '/elderly/relative',
    method: 'post',
    data: data
  })
}

// 7. 修改亲属画像
export function updateRelativeProfile(data) {
  return request({
    url: '/elderly/relative',
    method: 'put',
    data: data
  })
}

// 8. 查询亲属画像列表（完整信息，包含文件数据）
export function getRelativeList(userId) {
  return request({
    url: `/elderly/relative/relativeList?userId=${userId}`,
    method: 'get'
  })
}

// 8.1 查询亲属画像列表（基础信息，不包含文件数据）
export function getRelativeListBasic(userId) {
  return request({
    url: `/elderly/relative/selectRelativeList?userId=${userId}`,
    method: 'get'
  })
}

// 9. 查询单个亲属画像
export function getRelativeProfile(relativeId) {
  return request({
    url: `/elderly/relative/${relativeId}`,
    method: 'get',
    timeout: 60000
  })
}

// 10. 获取对话记录
export function getChatHistory(userId, relativeId) {
  const data = {
    userId,
    relativeId
  }
  return request({
    url: '/elderly/log/selectLimit',
    method: 'post',
    data: data
  })
}

// 11. 新增提醒事项
export function addReminder(data) {
  return request({
    url: '/elderly/reminders',
    method: 'post',
    data: data
  })
}

// 11. 修改提醒事项
export function updateReminder(data) {
  return request({
    url: '/elderly/reminders',
    method: 'put',
    data: data
  })
}

// 12. 获取提醒事项列表
export function getReminderList(userId, pageNum = 1, pageSize = 10, params = {}) {
  const q = new URLSearchParams()
  q.set('pageNum', pageNum)
  q.set('pageSize', pageSize)
  if (userId) q.set('userId', userId)
  if (params.startDate) q.set('startDate', params.startDate)
  if (params.endDate) q.set('endDate', params.endDate)
  const qs = q.toString()
  return request({
    url: `/elderly/reminders/selList${qs ? `?${qs}` : ''}`,
    method: 'get'
  })
}

// 13. 获取系统字典
export function getDictData(dictType) {
  return request({
    url: `/system/dict/data/type/${dictType}`,
    method: 'get'
  })
}

// 14. 文件上传API
export function uploadFile(file) {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/common/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 15. uni-app专用文件上传API（已废弃，使用 uploadRelativeFileNew 替代）
// export function uploadFileUni(file) {
//   // 此函数已废弃，请使用 uploadRelativeFileNew
//   throw new Error('uploadFileUni 已废弃，请使用 uploadRelativeFileNew');
// }

// 获取常用字典数据的便捷方法
export function getCommonDicts() {
  const dictTypes = [
    'gender',                    // 性别
    'spouse_status',            // 配偶状态
    'living_situation',         // 居住情况
    'speech_rate_preference',   // 语速偏好
    'speech_impairment',        // 语言障碍
    'needs_nighttime_companion' // 夜间陪伴
  ]
  
  const promises = dictTypes.map(type => getDictData(type))
  return Promise.all(promises).then(results => {
    const dicts = {}
    dictTypes.forEach((type, index) => {
      dicts[type] = results[index].data || []
    })
    return dicts
  })
}

// 便捷方法：获取AI对话记录（relativeId=0）
export function getAIChatHistory(userId) {
  return getChatHistory(userId, 0)
}

// 便捷方法：获取与特定亲属的对话记录
export function getRelativeChatHistory(userId, relativeId) {
  return getChatHistory(userId, relativeId)
}

// 37. 新文件上传接口
export function uploadRelativeFileNew(files, userId, fileType, relativeId = '') {
  return new Promise((resolve, reject) => {
    try {
      // 使用标准的 fetch API 处理文件上传（适用于PC端）
      const formData = new FormData();
      formData.append('files', files);
      formData.append('userId', userId);
      formData.append('fileType', fileType);
      
      // 只有当 relativeId 不为 null 或 undefined 时才添加到 FormData
      if (relativeId !== null && relativeId !== undefined) {
        formData.append('relativeId', relativeId);
      }
      
      console.log('Uploading file:', {
        file: files,
        userId: userId,
        fileType: fileType,
        relativeId: relativeId,
        relativeIdType: typeof relativeId,
        relativeIdIsNull: relativeId === null,
        relativeIdIsUndefined: relativeId === undefined,
        url: config.baseUrl + '/elderly/files/addFlie'
      });
      
      fetch(config.baseUrl + '/elderly/files/addFlie', {
        method: 'POST',
        headers: {
          'Authorization': getToken() ? ('Bearer ' + getToken()) : ''
        },
        body: formData
      })
      .then(response => {
        console.log('Upload response status:', response.status);
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
      })
      .then(data => {
        console.log('Upload response data:', data);
        resolve(data);
      })
      .catch(error => {
        console.error('Upload fetch error:', error);
        reject(error);
      });
    } catch (error) {
      console.error('Upload setup error:', error);
      reject(error);
    }
  });
}

// 38. 新文件删除接口
export function deleteRelativeFile(ids) {
  return request({
    url: `/elderly/files/${ids}`,
    method: 'delete'
  })
}

// 39. 删除亲属接口
export function deleteRelative(relativeId) {
  return request({
    url: `/elderly/relative/del/${relativeId}`,
    method: 'delete'
  })
}

// 40. 删除提醒接口
export function deleteReminder(id) {
  return request({
    url: `/elderly/reminders/del/${id}`,
    method: 'delete'
  })
}
